﻿using PLCS.Domain.Orders;
using PLCS.EntityFrameworkCore.EntityFrameworkCore;

namespace PLCS.EntityFrameworkCore.Orders
{
    internal class HisOrderRepository : EfCoreRepository<PLCSDbContext, HisOrder, Guid>, IHisOrderRepository
    {
        public HisOrderRepository(IDbContextProvider<PLCSDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<HisOrder?> FindHisOrderByNoAsync(string orderNo)
        {
            var dbContext = await GetDbContextAsync();
            var hisOrder = await FindAsync(x => x.OrderNo == orderNo);
            if (hisOrder != null)
                hisOrder.OrderRunningConditions = await dbContext.OrderRunningConditions.Where(x => x.OrderNo == hisOrder.OrderNo).OrderBy(x => x.WhichStep).ToListAsync();
            return hisOrder;
        }

        public async Task<IEnumerable<HisOrder>> GetHisOrderListAsync(Expression<Func<HisOrder, bool>> predicate)
        {
            var dbContext = await GetDbContextAsync();
            var hisOrders = await GetListAsync(predicate);
            foreach (var item in hisOrders)
            {
                item.OrderRunningConditions = await dbContext.OrderRunningConditions.Where(x => x.OrderNo == item.OrderNo).OrderBy(x => x.WhichStep).ToListAsync();
            }
            return hisOrders;
        }

        public async Task<IEnumerable<HisOrder>> GetHisOrderListAsync()
        {
            var dbContext = await GetDbContextAsync();
            var hisOrders = await GetListAsync();
            foreach (var item in hisOrders)
            {
                item.OrderRunningConditions = await dbContext.OrderRunningConditions.Where(x => x.OrderNo == item.OrderNo).OrderBy(x => x.WhichStep).ToListAsync();
            }
            return hisOrders;
        }

        public async Task<IEnumerable<HisOrder>> GetListByTimeAsync(string startTime, string endTime)
        {
            var dbContext = await GetDbContextAsync();
            var hisOrders = dbContext.HisOrders.WhereIf(!string.IsNullOrEmpty(startTime), x => x.CreationTime > DateTime.Parse(startTime))
                .WhereIf(!string.IsNullOrEmpty(endTime), x => x.CreationTime < DateTime.Parse(endTime));
            foreach (var item in hisOrders)
            {
                item.OrderRunningConditions = await dbContext.OrderRunningConditions.Where(x => x.OrderNo == item.OrderNo).OrderBy(x => x.WhichStep).ToListAsync();
            }
            return hisOrders.ToList();
        }
    }
}